/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, useTheme, Table, TableBody, TableRow, Cell, CCell, Button, Collapse, TableHead,
} from "customize-easy-ui-component";
import { DirectLink } from "../../../routing/Link";
import {CCellUnit, ReportViewProps, ReportViewSubProps,} from "../../common/base";
import {
    分项末尾链接,
} from "../../common/rarelyVary";
import {multilines2Html} from "../../tools";
import {useMainRepUrlOr, useSplitSubCapacity, useSplitSubRepList} from "../../hook/useMainRepUrlOr";
import HashLinkObserver from "react-hash-link";
import {config射线源, config测量仪, config评定, model工件, } from "./orcBase";
import {useRepTableViewer} from "../../hook/useRepTableEditor";
import {useContext} from "react";
import RoutingContext from "../../../routing/RoutingContext";
import {useThreeColumnSubr} from "../../hook/useThreeColumnSubr";
import {NameFiledAs} from "../../common/ftable";


/**@param fxIdx: 独立流转模式的 分项序号的基数； 若是嵌入式的分项该参数=undefined! rep?.id!==repId
 * 只要是公共的模板：那modelConfigs.ts就不能少了配置该模板代码。
 * */
export const ReportView: React.FunctionComponent<ReportViewProps> = (
    {repId,   source: parentOrc,  verId,rep, redId,fxIdx ,...other}
) => {
    const {urlMainRep}=useMainRepUrlOr(rep);
    const lsBlockMax=useSplitSubCapacity(parentOrc?._RADIO_TS?.length,1);       //【模板敲定一次性最大几个分项显示出来】有些分项报告模板可能存在很多个分项 最多1个
    const {sumArea, areaIdAs, btnBindUses}=useSplitSubRepList(parentOrc?._RADIO_TS ?? [], lsBlockMax,false);
    const { get:getRouteUrl } = useContext(RoutingContext);
    const routeLevels=getRouteUrl().entries.length;
    const routeTemplate=getRouteUrl().entries[routeLevels-1]?.routeData?.params?.template;
    return (
     <React.Fragment>
      <div  id="rp_radio_"  css={{"@media not print": {marginTop:'1rem', marginBottom: '1rem'},}}>
         <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/RADIO_TS/_Controller`}>
            <div css={{"@media print":{display: 'none'} }}>
                <Button>{(repId===rep?.id && rep?.modeltype!=='RADIO_TS')? '内嵌式的':'独立流转的'}射线检测报告分项控制器</Button>
            </div>
         </DirectLink>
        {(new Array(sumArea).fill(null)).map((s:any,ak:number) => {
            const [isDisplay, bindBtn]=btnBindUses[ak];      //不要加上 tabIndex={0} 超过折叠区域最大数量的？
            //可折叠区的：独立流转的报告，和内嵌分项的，实际还分开的。两者独自控制折叠的。内嵌分项rep.id相等，独立流转的却不等的ID;
            return <React.Fragment key={ak}>
                <div key={ak} role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                    { <Text variant="h4">{`射线检测折叠区${ak+1}，`}{isDisplay ? `收起`:`更多..`}</Text> }
                </div>
                <Collapse id={`${ak}`} show={isDisplay} noAnimated>
                    { areaIdAs[ak]?.map((surpId: any, m:number) => {
                        const dispIdx=(fxIdx??0) +(m+ ak*lsBlockMax);
                        return <OneSubRepView key={m} fxIdx={fxIdx} dispIdx={dispIdx} rep={rep} repId={repId}
                                              verId={verId} parentOrc={parentOrc} surpId={surpId}/>
                    }) }
                    <div role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                        <Text variant="h4">{`射线检测折叠区${ak+1}结束,收起`}</Text>
                    </div>
                </Collapse>
            </React.Fragment>
        })}
      </div>
      {分项末尾链接({template:'RADIO_TS', repId: repId||'',verId,urlMainRep,
            nestIn:'RADIO_TS'!==routeTemplate, flowNest: repId!==rep?.id}) }
     </React.Fragment>
    );
}

const UpModelPart= model工件.slice(0,5);
const DownModelPart= model工件.slice(5);
/**为了用上useRepTableViewer，就只能从上级组件脱离分出来
 * 唯独只有一个的分项报告的。
 * @param fxIdx: 独立流转模式的 分项序号的基数； 若是嵌入式的分项该参数=undefined! rep?.id!==repId
 * 附页：可能有图的 整页height: '96vh' +底下一个行的。
 * */
const OneSubRepView: React.FunctionComponent<ReportViewSubProps> = (
    {fxIdx,dispIdx,rep,repId,verId,parentOrc,surpId}
) => {
    const theme= useTheme();
    const orc=parentOrc['_RADIO_TS_'+surpId];
    const [_,renderRows]=useRepTableViewer(config评定, '评定表', orc,true,true);
    //可直接按行分解变身几个部分！每个独立再来拼装的。
    const [firstNode,secondNode]=useThreeColumnSubr({orc, config:config测量仪,parentOrc,split:[5],
                        href:`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/Instrument`});

    return <React.Fragment>
        <div css={{marginTop: '1rem', "@media print": {pageBreakInside: 'avoid',marginTop:'unset'} }}>
            <Text variant="h2" css={{textAlign:'center',}}>
              射线检测报告{dispIdx? '-'+dispIdx : ''}
            </Text>
            <div css={{display: 'flex', justifyContent: 'flex-end', flexDirection: 'row',}}>
                <Text  css={{[theme.mediaQueries.md]: {marginRight: '2rem',}}}>
                 报告编号：{rep.isp.no}
                </Text>
            </div>
            <Table fixed={ ["10%","22%","10%","22%","10%","%"] } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                <TableBody>
                    {firstNode}
                    {secondNode}
                </TableBody>
            </Table>
        </div>
        <Table  fixed={ ["13%","%","10%","12%","14%","9%","21%"]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableBody>
                <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/PartSummary#PartSummary`}>
                    { UpModelPart.map(([orgDesc,nameObj,cb]: any, i:number)=> {
                        const {n: name} = nameObj as NameFiledAs;
                        const desc = typeof orgDesc === 'string' ? orgDesc : orgDesc?.view;         //这个view 和 text分别针对是报告和编辑器的标题
                        return <React.Fragment key={i}>
                            <TableRow key={i}>
                                <CCell key={0}>{desc}</CCell>
                                {(new Array(4)).fill(null).map(( _,  w:number) => {
                                    return <CCell key={w+1} colSpan={(w===1 ||w===2)? 2:1}>{orc?.工件表?.[w]?.[name]??'／'}</CCell>;
                                }) }
                            </TableRow>
                        </React.Fragment>;
                    }) }
                </DirectLink>
                <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/ResultDiagram#ResultDiagram`}>
                    <TableRow>
                        { config射线源.map(({t,n,u}, i:number)=> {
                            return <React.Fragment key={i}>
                                <CCell>{t}</CCell><CCellUnit colSpan={1===i? 2:1} unit={u}>{orc?.[n]??'／'}</CCellUnit>
                            </React.Fragment>;
                        })}
                    </TableRow>
                </DirectLink>
                <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/PartSummary#PartSummary`}>
                    { DownModelPart.map(([orgDesc,nameObj,cb]: any, i:number)=> {
                        const {n: name} = nameObj as NameFiledAs;
                        const desc = typeof orgDesc === 'string' ? orgDesc : orgDesc?.view;         //这个view 和 text分别针对是报告和编辑器的标题
                        return <React.Fragment key={i}>
                            <TableRow key={i}>
                                <CCell key={0}><Text css={{fontSize: i===3?'0.65rem':i===4?'0.8rem':'0.875rem'}}>{desc}</Text></CCell>
                                {(new Array(4)).fill(null).map(( _,  w:number) => {
                                    return <CCell key={w+1} colSpan={(w===1 ||w===2)? 2:1}>{orc?.工件表?.[w]?.[name]??'／'}</CCell>;
                                }) }
                            </TableRow>
                        </React.Fragment>;
                    }) }
                </DirectLink>
            </TableBody>
        </Table>
        <Table fixed={ ["62%","%"]  }  css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableBody>
                <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/ResultDiagram`}>
                    <TableRow>
                        <Cell split={true} colSpan={2}><div css={{ minHeight: '2rem' }}>
                            检测结果：<br/>
                            {  multilines2Html(orc?.检测结果,  (txt,i)=>{
                                return <React.Fragment key={i}>{(i!==0)&&<br/>}<Text>{txt}</Text></React.Fragment>
                            } ) }</div></Cell>
                    </TableRow>
                </DirectLink>
              <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/ResultDiagram`}>
                <TableRow>
                    <Cell colSpan={2} split={true}
                          css={{"@media print": {height: orc?._FILE_S部位 ? '93vh' : undefined}, padding: 0}}>
                        检测部位（布片示意图）：<br/>
                        {multilines2Html(orc?.示图说明, (txt, i) => {
                            return <React.Fragment key={i}>{(i !== 0) && <br/>}<Text>{txt}</Text></React.Fragment>
                        })}

                        { orc?._FILE_S部位?.map(({name,url} : any, i:number) => {
                            return <div key={i} css={{"@media print": {pageBreakInside: 'avoid' } }}>
                                     {i>0 && <hr/>}
                                     <div css={{display: 'flex',justifyContent: 'space-around',alignItems: 'center',}}>
                                        { url &&
                                            <img src={process.env.REACT_APP_OSS_ENDP+url} alt={url}
                                                 css={{
                                                     maxHeight: '14cm',   //在这个元素的上一级元素可以自己加一个固定高度值，就像一张纸打印的应该多高的取值。这个用固定高度会导致图片自动的横竖比例不均衡压缩=会变形啊！24cm是纸张大约最多高度=报告最大图片高。
                                                     maxWidth: '-webkit-fill-available',
                                                     [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},           //普通图片+大屏幕限制高度才是关键的。
                                                     //【很容易超过限制！！】A4纸规格21cm×29.7cm，扣除页眉页脚再扣除 tr td以及高度方向上的其它DOM：标题高度，其它tr行高。
                                                     //打印css：需要在<td>上加height: 86vh盛满整张纸张后，能保证图片正常打印。 打印时: 小图片不会主动放大的。
                                                     "@media print": {maxHeight: '86vh', maxWidth: '100%'},        //对A4纸张竖版的高度26cm基本都是图片整张纸，这里没考虑多个图片在宽度方向上的并排布局：可用软件合并。
                                                 }}
                                            />
                                        }
                                    </div>
                             </div>
                        }) }
                    </Cell>
                </TableRow>
              </DirectLink>
            </TableBody>
        </Table>
        <Table  fixed={ ["14%","12%","15%","%","7%","23%"]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableHead>
              <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/EvaluationForm`}>
                <TableRow><CCell colSpan={6}><Text css={{fontSize:'0.75rem'}}>射 线 检 测 底 片 评 定 表</Text></CCell></TableRow>
                <TableRow>
                  {config评定.map(([title,_2,_1], i:number) => {
                      return <CCell key={i}><Text css={{fontSize: (i===4 || i===1)?'0.7rem':'0.875rem'}}>{title}</Text></CCell>;
                  }) }
                </TableRow>
              </DirectLink>
            </TableHead>
            <TableBody>
                <DirectLink  href={`/report/RADIO_TS/ver/${verId}/${repId}/${surpId}/EvaluationForm#EvaluationForm`}>
                    {renderRows}
                </DirectLink>
            </TableBody>
        </Table>
        <Table fixed={ ["9%","%","9%","18%","7%","14%"]  }  css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableBody>
                <TableRow>
                    <CCell>检验：</CCell><CCell></CCell>
                    <CCell>级别</CCell><CCell>UT－Ⅱ</CCell><CCell>日期</CCell><CCell>2024-03-20</CCell>
                </TableRow>
                <TableRow>
                    <CCell>审核：</CCell><CCell></CCell>
                    <CCell>级别</CCell><CCell>UT－Ⅲ</CCell><CCell>日期</CCell><CCell>2024-03-22</CCell>
                </TableRow>
            </TableBody>
        </Table>
    </React.Fragment>;
}

